package gas.frontend;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.HashMap;

public class ScanIR {
	private String filename;
	private int lineCount = 0;
	private HashMap<String, Integer> labelList = new HashMap<String, Integer>();
	private HashMap<String, Integer> lineList = new HashMap<String, Integer>();
	public ScanIR (String filename, HashMap<String, Integer> gotoIndex){
		this.filename = filename;
		this.labelList = gotoIndex;
	}

	public void Scan(){

		try {
			FileReader fr = new FileReader(filename);
			BufferedReader br = new BufferedReader(fr);
			FileWriter outFile;
			outFile = new FileWriter("/home/kuangye/Dropbox/workspace/plt2009/test2.o");
			PrintWriter out = new PrintWriter(outFile);

			String line = br.readLine();
			String tokens[] = line.split(" ");

			while(line != null){
				tokens = line.split(" ");
				if(labelList.containsKey(tokens[0])){
					lineList.put(tokens[0], new Integer(lineCount));
				}
				lineCount++;
				line = br.readLine();
			}

			FileReader fr2 = new FileReader(filename);
			BufferedReader br2 = new BufferedReader(fr2);		

			line = br2.readLine();

			while(line != null) {
				tokens = line.split(" ");
				if(lineList.containsKey(tokens[0])){
					line = line.substring(line.indexOf(" ") + 1, line.length());
				}
				for (String it : tokens){
					if(lineList.containsKey(it)){
						line = line.replaceAll(it, lineList.get(it).toString());
					}
				}
				out.print(line + "\n");
				line = br2.readLine();
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}